package com.ykdl.member.kid.marketcard;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import oauth.signpost.http.HttpParameters;
import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.kid.R;
import com.ykdl.member.KidApp;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.http.Network;
import com.ykdl.member.kid.beans.Actor_InfoBean;
import com.ykdl.member.kid.beans.AvatarBean;
import com.ykdl.member.kid.beans.GetFileMate;
import com.ykdl.member.kid.beans.GetProfileBean;
import com.ykdl.member.kid.beans.GetUser_ScoreBean;
import com.ykdl.member.kid.beans.ProfileBean;
import com.ykdl.member.kid.beans.RegisterPhonebean;
import com.ykdl.member.kid.beans.ResultBean;
import com.ykdl.member.kid.beans.StatuResult;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.models.FileMetas;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.set.MybabyActivity;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.CalendarUtil;
import com.ykdl.member.kid.util.CameraHelp;
import com.ykdl.member.kid.util.DateUtil;
import com.ykdl.member.kid.util.StringUtils;
import com.ykdl.member.kid.widget.AsyncImageView;
import com.ykdl.member.views.MyWheelView;
import com.ykdl.member.views.MyWheelView.OnWheelViewDataChanger;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class CardPersonalInformationActivity extends BaseScreen implements OnClickListener {
	public static final String TAG = "CardPersonalInformationActivity";

	private LinearLayout layout_photomenu;
	private CameraHelp mSurveyCameraHelp;
	private ImageView headimg;
	private TextView gender, city_tv;
	private ImageView mImgSex;
	private String picpath = "";
	final String[] genderaray = new String[] {"女宝宝","男宝宝"};
	private MyWheelView location;
	private BitmapUtils bitmapUtil ;
	// private String locationStr;
	final static private int UPLOAD_TEXT = 1;
	final static private int UPLOAD_HEAD = 2;
	/**
	 * 等待图片上传的结果
	 */
	private boolean waitImg = false;

	/**
	 * 等待文字上传的结果
	 */
	private boolean waitText = false;

	/**
	 * 图片上传失败
	 */
	private boolean imageErr = false;
	private EditText nickname_et;
	TextView age_et;

	/**
	 * 可以从 我的主页和设置里进来,null,来自我的主页，有值，来自设置
	 */
	private MyWheelView wheel_time;
	
	private int gender_index;
	
	private int file_id;
	private BitmapUtils mBmpUtils;
	private ProgressDialog mProgressDialog;
	private boolean open = false ;
	private boolean iopen = false ;
	private long babybirthday ;
	private static AccessTokenKeeper mTokenKeeper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTopTitle("编辑个人资料", 0, R.drawable.back_bg, new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		}, 0,
		R.drawable.save_bt_bg, new OnClickListener() {

					@Override
					public void onClick(View v) {
						save();
					}

				}, 0);

		setContent(R.layout.cardpersonalinformationactivity);
		mSurveyCameraHelp = new CameraHelp(CardPersonalInformationActivity.this);
		mSurveyCameraHelp.setOutputX(100);
		mSurveyCameraHelp.setOutputY(100);
		mSurveyCameraHelp.setAspectX(5);
		mSurveyCameraHelp.setAspectY(5);
		mSurveyCameraHelp.setmNeedzoom(true);
		bitmapUtil = new BitmapUtils(this);
		bitmapUtil.configDefaultLoadingImage(R.drawable.defualt_icon);
		bitmapUtil.configDefaultLoadFailedImage(R.drawable.defualt_icon);
		mTokenKeeper = new AccessTokenKeeper(this);
		initViews();

		wheel_time = (MyWheelView) findViewById(R.id.accountinfor_wheel_time);
		wheel_time.setVisibility(View.INVISIBLE);
		wheel_time.setWheelView(MyWheelView.CALENDAR);
wheel_time.findViewById(R.id.my_wheelview_cancel).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				open = false;
				wheel_time.setMyGone();
			}
		});
		wheel_time.setOnWheelViewDataChanger(new OnWheelViewDataChanger() {

			@Override
			public void updataByChanger(String data) {
				if (!open) {
					InputMethodManager mInputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
					mInputMethodManager.toggleSoftInput(0, InputMethodManager.RESULT_UNCHANGED_SHOWN);
					
				} else {
					String[] time = data.split(",");
					age_et.setText(time[0]
							+ "年"
							+ time[1]
							+ "月"
							+ time[2]
							+ "日     "
							);
					open = false;
					Date now = new Date();
					now.setYear(Integer.parseInt(time[0])-1900);
					now.setMonth(Integer.parseInt(time[1])-1);
					now.setDate(Integer.parseInt(time[2]));
					babybirthday =now.getTime()/1000;
				}
				

			}
		});

		findViewById(R.id.edit_babyinfor).setOnClickListener(this);
		mBmpUtils = new BitmapUtils(this);
		// 初始化数据
		getData();
		
	}
	public void getData() {
		showProgress("正在加载中,请稍等...");
		String  pageurl =KidConfig.GET_MYSELF;
		HttpParameters parameterss = new HttpParameters();
		HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl,parameterss,null);
		 TaskManager.startHttpRequest(request, new getDataTag(),  GetUser_ScoreBean.class);
	}
	
	class getDataTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof GetUser_ScoreBean) {
				GetUser_ScoreBean bean = (GetUser_ScoreBean)t;
				fillData(bean.getActor_info());
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}

	/**
	 * 保存 头像到本地
	 * 
	 * @param purl
	 * @param count
	 * @return
	 */
	public static String saveImgToLocal(String purl, int count) {
		String filename = "";
		try {
			int index = purl.lastIndexOf("/");
			File dir = new File(Environment.getExternalStorageDirectory()
					+ KidConfig.HEAD_PATH);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			filename = dir + purl.substring(index);
			filename = filename.replace("?", "_");
			File outcache = new File(filename);
			if (outcache.exists()) {
				outcache.delete();
			}

			URL url = new URL(purl);
			InputStream in = url.openStream();
			FileOutputStream out = new FileOutputStream(filename);
			byte[] buffer = new byte[1024];
			int read;
			while ((read = in.read(buffer)) != -1) {
				out.write(buffer, 0, read);
			}

		} catch (Exception e) {
			e.printStackTrace();
			if (count == 1) {
				return saveImgToLocal(purl, 2);
			}
		}
		return filename;
	}

	private void initViews() {
		location = (MyWheelView) findViewById(R.id.select_location_layout);
		headimg = (ImageView) findViewById(R.id.iask_head_btn);
		gender = (TextView) findViewById(R.id.iask_gender);
		mImgSex = (ImageView) findViewById(R.id.imgSex);
		nickname_et = ((EditText) findViewById(R.id.iask_nick));
		city_tv = ((TextView) findViewById(R.id.iask_city));
		age_et = ((TextView) findViewById(R.id.iask_age));
		age_et.setOnClickListener(this);
		findViewById(R.id.layerSex).setOnClickListener(this);
		city_tv = (TextView) findViewById(R.id.iask_city);
		city_tv.setOnClickListener(this);

		findViewById(R.id.iask_account_head).setOnClickListener(this);
		layout_photomenu = (LinearLayout) this.findViewById(R.id.iask_selphoto);
		layout_photomenu.setFocusable(true);
		layout_photomenu.setFocusableInTouchMode(true);
		findViewById(R.id.photograph).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						mSurveyCameraHelp.selectImageFromCamera();
						layout_photomenu.setVisibility(View.GONE);

					}
				});
		findViewById(R.id.album).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mSurveyCameraHelp.selectImageFromLocal();
				layout_photomenu.setVisibility(View.GONE);
			}
		});
		findViewById(R.id.cencel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						layout_photomenu.setVisibility(View.GONE);
					}
				});

		location.setWheelView(MyWheelView.CHINA);
		// LinearLayout mWheelViewGroup = (LinearLayout) mMyWheelView
		// .findViewById(R.id.my_wheelview_group);
		// mWheelViewGroup.removeViewAt(2);
		location.setVisibility(View.INVISIBLE);
		location.findViewById(R.id.my_wheelview_cancel).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				iopen = false;
				location.setMyGone();
			}
		});
		location.setOnWheelViewDataChanger(new OnWheelViewDataChanger() {
			@Override
			public void updataByChanger(String data) {
				if (!iopen) {
					InputMethodManager mInputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
					mInputMethodManager.toggleSoftInput(0, InputMethodManager.RESULT_UNCHANGED_SHOWN);
					
				} else {
					QLog.debug("data", data);
					String[] datas = data.split("&#&");
					String[] contents = datas[0].split(",");
					String result = "";
					for (int i = 0; i < contents.length; i++) {
						if (!"".equals(result)) {
							result += "，";
						}
						result += contents[i];
					}
					city_tv.setText(result);
					iopen = false;
					
				}
				
			}
		});

	}
	
	private void fillData(Actor_InfoBean profile){
		if (profile == null) {
			return;
		}
		if (null!=profile.getAvatar_info()) {
			bitmapUtil.display(headimg, profile.getAvatar_info().getFile_url());
		}
		nickname_et.setText(profile.getDisplay_name());
		if ("1".equals(profile.getGender())) {
			gender.setText(genderaray[1]);
			mImgSex.setImageResource(R.drawable.icon_male);
			gender_index = 1;
		} else {
			gender.setText(genderaray[0]);
			mImgSex.setImageResource(R.drawable.icon_female);
			gender_index = 0;
		}
		city_tv.setText(profile.getAddress());
		if (!TextUtils.isEmpty(profile.getBirthday())) {
			babybirthday=Long.parseLong(profile.getBirthday());
			age_et.setText(DateUtil.getTopicDate(profile.getBirthday()));
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edit_babyinfor:
			//宝宝设置页面
			go(MybabyActivity.class);
			break;
		case R.id.iask_account_head:
			layout_photomenu.setVisibility(View.VISIBLE);
			break;
		case R.id.iask_age:
			wheel_time.setVisibility(View.VISIBLE);
				open = true;
				((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(CardPersonalInformationActivity.this.getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  
				wheel_time.setInVisible(true);
				wheel_time.setMyVisible();
			break;
		case R.id.layerSex:
			String tt = gender.getText().toString();
			AlertDialog alertDialog = new AlertDialog.Builder(
					CardPersonalInformationActivity.this).setSingleChoiceItems(genderaray,
						gender_index, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							gender.setText(genderaray[which]);
							if (which == 1) {
								mImgSex.setImageResource(R.drawable.icon_male);
							} else {
								mImgSex.setImageResource(R.drawable.icon_female);
							}
							gender_index = which;
							dialog.cancel();
						}
					}).create();
			alertDialog.show();
			break;
		case R.id.iask_city:
			iopen = true;
			location.setVisibility(View.VISIBLE);
			((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
			.hideSoftInputFromWindow(CardPersonalInformationActivity.this.getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  
			location.setInVisible(true);
			location.setMyVisible();
			break;
		default:
			break;
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (/* CameraHelp.SURVEY_CAMERA_WITH_DATA == requestCode &&& */resultCode == RESULT_OK) {
			try {
				picpath = mSurveyCameraHelp.setPicture(requestCode, resultCode,
						data);
				File file = new File(picpath);
				putphoto(file);  
				headimg.setImageURI(Uri.parse(picpath));  
				headimg.setBackgroundDrawable(null);
			} catch (Throwable ee) {
				QLog.debug(TAG, "内存不足===!!!!!!1");
				Toast.makeText(this, "内存不足", Toast.LENGTH_SHORT).show();
				// System.gc();
				picpath = "";
			}
			QLog.debug(TAG, "picpath===" + picpath);
		}
		if (requestCode == CameraHelp.SURVEY_PHOTO_ZOOM) {
//			headimg.setImageURI(Uri.parse(picpath));
//			headimg.setBackgroundDrawable(null);
		}

	}
	
	@Override
	public void onBackPressed() {
		if (layout_photomenu.getVisibility() == View.VISIBLE ||
				wheel_time.getMyVisibility()  == View.VISIBLE) {
			
		} 
		super.onBackPressed();
	}
	
	private void save(){
		String name = nickname_et.getText().toString().trim();
		/*if (TextUtils.isEmpty(name)) {
			Toast.makeText(this, "请输入姓名", 1).show();
			return;
		}*/
		
		if(StringUtils.chineseLength(name)<3 || StringUtils.chineseLength(name)>24){
			Toast.makeText(this, "用户昵称应在3-24个字符", 1).show();
			return;
		}
		String region = city_tv.getText().toString();
		if (TextUtils.isEmpty(region)) {
			Toast.makeText(this, "输入地区信息", 1).show();
			return;
		}
		String strDate = age_et.getText().toString();
		if (TextUtils.isEmpty(strDate)) {
			Toast.makeText(this, "请选择出生日期", 1).show();
			return;
		}
		showProgress(getString(R.string.progres_dialog_loading));
		Network.getInstance().perfectProfile(name, babybirthday, 
				region, gender_index, file_id, new ProfileTag());
	}
	
	
	
	class GetAvatarTag implements ITag<GetFileMate> {

		@Override
		public void refreshUI(GetFileMate t, DataState ds) {
			if (t != null && t.getAvatar() != null && t.getAvatar().getDownload_urls() != null &&
					t.getAvatar().getDownload_urls().getMiddle() != null &&
					!TextUtils.isEmpty(t.getAvatar().getDownload_urls().getMiddle().getUrl())) {
				mBmpUtils.display(headimg, t.getAvatar().getDownload_urls().getMiddle().getUrl());
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	public void putphoto(File file) {
		String  pageurl = KidConfig.UPDATE_AVATAR;
		HttpBaseRequest request  =  Wxxr.getInstance().uploadAvatar(pageurl,file);
		TaskManager.startHttpRequest(request, new PutphotoTag(),  AvatarBean.class);
	}
	
	class PutphotoTag implements ITag<AvatarBean> {

		@Override
		public void refreshUI(AvatarBean t, DataState ds) {
			// TODO Auto-generated method stub
			if (t != null) {
				// TODO 完善资料接口还没有file_id
				AvatarBean bean=(AvatarBean)t;
				if (bean.getError()==null) {
					Toast.makeText(CardPersonalInformationActivity.this, "头像上传成功", 1).show();
				}else {
					Toast.makeText(CardPersonalInformationActivity.this, "头像上传失败", 1).show();
				}
				}
				
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			if (parseError != null && !TextUtils.isEmpty(parseError.getErrMsg())) {
				Toast.makeText(CardPersonalInformationActivity.this, parseError.getErrMsg(), Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(CardPersonalInformationActivity.this, "头像上传失败", 1).show();
			}
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	private class ProfileTag implements ITag<GetUser_ScoreBean> {

		@Override
		public void refreshUI(GetUser_ScoreBean t, DataState ds) {
			if (mProgressDialog != null) mProgressDialog.dismiss();
			finishProgress();
			if (t instanceof GetUser_ScoreBean) {
				GetUser_ScoreBean bean = (GetUser_ScoreBean)t;
				if(null==bean.getError()){
					Toast.makeText(CardPersonalInformationActivity.this, "保存成功", 1).show();
				}else {
					Toast.makeText(CardPersonalInformationActivity.this, "保存失败,"+bean.getDesc(), 1).show();
				}
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			if (mProgressDialog != null) mProgressDialog.dismiss();
			Toast.makeText(CardPersonalInformationActivity.this, "个人详细信息设置失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}

}
